package com.feiyun.util;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.feiyun.mapper.UserMapper;
import com.feiyun.model.entity.User;

/**
 * Function Desc:
 *
 * @author yan
 * @since 2023/4/14 21:12
 */

@Component
@RequiredArgsConstructor
public class JWTUtils {
    @Value("${jwt.secretKey}")
    private String secretKey;

    private final UserMapper userMapper;

    /**
     * 创建TOKEN
     *
     * @param userId userId
     * @return token
     */
    public String createToken(int userId) {
        return JWT.create()
                .withClaim("userId", userId)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(secretKey));
    }


    /**
     * 解析token
     * {
     * "userId": "123",
     * "timeStamp": "134143214"
     * }
     */
    public Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<>();
        DecodedJWT decodedJWT = JWT
                .require(Algorithm.HMAC256(secretKey))
                .build()
                .verify(token);
        Claim userId = decodedJWT.getClaim("userId");
        Claim timeStamp = decodedJWT.getClaim("timeStamp");

        map.put("userId", userId.asString());
        map.put("timeStamp", timeStamp.asLong().toString());
        return map;
    }

    /**
     * 获取当前请求的用户信息
     *
     * @param request req
     * @return User
     */
    public User getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String, String> map = this.parseToken(token);
        String userId = map.get("userId");
        return userMapper.selectById(userId);
    }
}
